package com.cawis.config;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.ObjectUtils;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Configuration
public class GatewayFilter implements GlobalFilter, Ordered {

    /**
     * 忽略的URL
     */
    @Value("${config.excludes}")
    private String[] excludes;

    /**
     * 跨域-Origin
     *
     * @return
     */
    @Bean
    public CorsWebFilter corsFilter() {
        CorsConfiguration cors = new CorsConfiguration();
        cors.setAllowedOriginPatterns(Collections.singletonList("*"));
        for (String exclude : excludes) {
            cors.addAllowedOrigin(exclude);
        }
        cors.addAllowedHeader(CorsConfiguration.ALL);
        cors.addAllowedMethod(CorsConfiguration.ALL);
        cors.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", cors);
        return new CorsWebFilter(source);
    }

    /**
     * 防盗链-Referer
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        Map<String, String> headers = request.getHeaders().toSingleValueMap();
        String referer = headers.get(HttpHeaders.REFERER);
        URI uri = request.getURI();
        //已忽略的URL不拦截
        if (isExcludeUrl(referer + uri.getPath())) {
            return chain.filter(exchange);
        }
        //是否存在外链请求本站
        if ((null != referer && referer.indexOf(uri.getHost()) < 0)) {
            log.info("Referer过滤器 => 服务器：{} => 当前域名：{} => 当前url:{}", uri.getHost(), referer, uri.getPath());
            Map data = new HashMap<>();
            data.put("code", 1002);
            data.put("data", "系统不支持当前域名访问");
            DataBuffer dataBuffer = response.bufferFactory().wrap(JSONObject.toJSONString(data).getBytes());
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            return response.writeWith(Mono.just(dataBuffer));
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -1;
    }

    /**
     * 判断是否为忽略的URL
     *
     * @param url URL路径
     * @return true-忽略，false-过滤
     */
    private boolean isExcludeUrl(String url) {
        return ObjectUtils.isEmpty(excludes) ? false : Arrays.asList(excludes).stream().map(pattern -> Pattern.compile("^" + pattern)).map(p -> p.matcher(url)).anyMatch(Matcher::find);
    }

}
